package com.kyzh.core.pager.weal.live

import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.gushenge.core.beans.LiveRoomBean
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.requests.LiveRequest
import com.kyzh.core.MyApplication
import com.kyzh.core.R
import com.kyzh.core.pager.login.LoginActivity
import com.kyzh.core.databinding.FragmentLiveBinding
import com.kyzh.core.databinding.ItemFragmentLiveBinding
import com.gushenge.core.base.fragment.BaseFragment
import com.kyzh.core.utils.im.TUIUtils
import com.kyzh.core.utils.startActivity
import com.kyzh.core.utils.startLogin
import com.gushenge.core.toast
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMGroupInfoResult
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tuicore.TUILogin
import org.jetbrains.anko.support.v4.onRefresh

class LiveFragment : BaseFragment() {
    companion object {
        fun newInstance(): LiveFragment {
            val args = Bundle()

            val fragment = LiveFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var list = arrayListOf<String>("1", "2")
    private val adapter = Adapter()
    private var bind: FragmentLiveBinding? = null
    private var mP = 1
    private var currentData = mutableListOf<LiveRoomBean>()

    //生成临时数据
    fun setcurrentd() {

        val liveRoomBean = LiveRoomBean(
            icon = "https://img.94hwan.com/2/20220630/zhibo_1.jpg" ,
                    supadmin_name = "只会打怪的主任",
            hot = "1",
            name = "全武器教学，带萌新过任务",
            status = "0"
        )
        val liveRoomBean1 = LiveRoomBean(
            supadmin_name = "狂鸟、黄小小",
            hot = "1",
            name = "搞起来！！播各种游戏",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_2.jpg",
        )
        val liveRoomBean2 = LiveRoomBean(
            supadmin_name = "暖风",
            hot = "2",
            name = "2k画质线上大镖客",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_3.webp",
        )
        val liveRoomBean3 = LiveRoomBean(
            supadmin_name = "简单、",
            hot = "3",
            name = "新服0606PVP，领跑全服",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_4.webp",
        )
        val liveRoomBean4 = LiveRoomBean(
            supadmin_name = "银雪生",
            hot = "4",
            name = "德棍白给日记",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_5.webp",
        )
        val liveRoomBean5 = LiveRoomBean(
            supadmin_name = "DM-陈辉",
            hot = "5",
            name = "4倍了，冲呀兄弟们",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_6.webp",
        )
        val liveRoomBean6 = LiveRoomBean(
            supadmin_name = "小艺PXP",
            hot = "5",
            name = "超高返利，白送648！",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_7.webp",
        )
        val liveRoomBean7 = LiveRoomBean(
            supadmin_name = "茶色、嗯迪",
            hot = "6",
            name = "工会招主播招兄弟带升级",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_8.webp",
        )
        val liveRoomBean8 = LiveRoomBean(
            supadmin_name = "盛世不争",
            hot = "7",
            name = "欢迎来到我的直播间~",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_9.webp",
        )
        val liveRoomBean9 = LiveRoomBean(
            supadmin_name = "下饭主播妖神",
            hot = "2",
            name = "开饭啦！",
            status = "0",
            icon = "https://img.94hwan.com/2/20220630/zhibo_10.webp",
        )
        currentData.add(liveRoomBean)
        currentData.add(liveRoomBean1)
        currentData.add(liveRoomBean2)
        currentData.add(liveRoomBean3)
        currentData.add(liveRoomBean4)
        currentData.add(liveRoomBean5)
        currentData.add(liveRoomBean6)
        currentData.add(liveRoomBean7)
        currentData.add(liveRoomBean8)
        currentData.add(liveRoomBean9)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        bind = FragmentLiveBinding.inflate(layoutInflater)
        return bind?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        bind?.init()

    }

    fun FragmentLiveBinding.init() {
        setcurrentd()
        rev.layoutManager = GridLayoutManager(requireContext(), 2)
        rev.adapter = adapter
        // 刷新
        swipe.onRefresh {
            mP = 1
            LiveRequest.geiLiveList(mP) {
                swipe.isRefreshing = false
                adapter.setNewInstance(this?.data)
                if (requireActivity().packageName == "a94hwan.bjkyzh.star") {
                    adapter.addData(currentData)
                }
                this?.apply {
                    adapter.loadMoreModule.loadMoreComplete()
                    if (mP >= max_p) {
                        adapter.loadMoreModule.loadMoreEnd(true)
                    }
                }
            }
        }
        //加载更多
        adapter.loadMoreModule.setOnLoadMoreListener {
            mP++
            LiveRequest.geiLiveList(mP) {
                this?.apply {
                    adapter.addData(this.data)
                    adapter.loadMoreModule.loadMoreComplete()
                    if (mP >= max_p) {
                        adapter.loadMoreModule.loadMoreEnd(true)
                    }
                }
            }
        }
        mP = 1
        LiveRequest.geiLiveList(mP) {

            adapter.setNewInstance(this?.data)
            if (requireActivity().packageName == "a94hwan.bjkyzh.star") {
                adapter.addData(currentData)
            }
            this?.apply {
                adapter.loadMoreModule.loadMoreComplete()
                if (mP >= max_p) {
                    adapter.loadMoreModule.loadMoreEnd(true)
                }
            }
        }
    }


    // 适配器
    inner class Adapter :
        BaseQuickAdapter<LiveRoomBean, BaseDataBindingHolder<ItemFragmentLiveBinding>>(R.layout.item_fragment_live),
        LoadMoreModule {
        override fun convert(
            holder: BaseDataBindingHolder<ItemFragmentLiveBinding>,
            item: LiveRoomBean
        ) {
            holder.dataBinding?.data = item
            if (item.status == "1" || !item.room_id.isNullOrBlank()) {
                holder.dataBinding?.tvLiveState?.text = "直播中"
                holder.dataBinding?.tvLiveState?.backgroundTintList = null
            } else {
                holder.dataBinding?.tvLiveState?.text = "未直播"
                holder.dataBinding?.tvLiveState?.backgroundTintList =
                    ColorStateList.valueOf(Color.parseColor("#575656"))
            }
            holder.itemView.setOnClickListener {
                if (MMKVConsts.imOpen && MyApplication.conIM) {
                    LiveRequest.geiLiveUserUid {
                        this?.apply {
                            TUILogin.login(live_uid, live_sign, object : V2TIMCallback {
                                override fun onSuccess() {
                                    if (startLogin()) {
                                        if (!MMKVConsts.imOpen) {
                                            "未配置直播参数".toast()
                                            return
                                        }
                                        if (item.status == "1" || !item.room_id.isNullOrBlank()) {
                                            V2TIMManager.getGroupManager()
                                                 .getGroupsInfo(arrayListOf(item.room_id), object :
                                                    V2TIMValueCallback<List<V2TIMGroupInfoResult>> {
                                                    override fun onSuccess(p0: List<V2TIMGroupInfoResult>?) {
                                                        p0?.apply {
                                                            Log.e(TUIUtils.TAGQUN, "onSuccess: " + p0[0].resultCode  + p0[0].resultMessage )

                                                            if (p0[0].resultCode == 0) {
                                                                LiveActivity.start(requireContext(), item.room_id)
                                                            } else {
                                                                "进入直播间失败".toast()
                                                            }
                                                        }

                                                    }

                                                    override fun onError(p0: Int, p1: String?) {
                                                        Log.e(TUIUtils.TAGQUN, "onError: $p0   $p1")
                                                        "登录失效，请重新登录".toast()
                                                        MMKVConsts.uid = ""
                                                        requireActivity().startActivity<LoginActivity>()
                                                    }

                                                })
                                        } else {
                                            "该房间暂未开播".toast()
                                        }
                                    }
                                }

                                override fun onError(p0: Int, p1: String?) {
                                    Log.e(TUIUtils.TAG, "onError: $p0  $p1")
                                }
                            })
                        }
                    }
                }else{
                    "未配置直播参数".toast()
                }

            }
        }
    }
}